/**
 * Created by chenzp on 18-9-4.
 */
layui.define(['jquery', 'layer'], function (exports) {

    var $ = layui.$


    /**
     * target转jquery对象
     * @param target
     */
    var jq = function (target) {

        if (!target) return

        var $jq = null

        if (typeof target == 'string' && target.trim().length) {

            if (target.startsWith('.') || target.startsWith('#')) {
                $jq = $(target)

            } else {

                $jq = $('#' + target).length ? $('#' + target) : null
            }

        } else if (typeof  target == 'object') {

            $jq = target.length ? target : null
        }

        return $jq
    }


    var ajax = function (url, option) {

        if (!url) {
            layer.msg('请求地址不能为空', {icon: 5});
            return
        }

        var isLoad = (option.loading == undefined || option.loading == null || option.loading == true) ? true : false

        if (isLoad) {
            var index = layer.load(0, {shade: false}) //0代表加载的风格，支持0-2
        }

        var opt = {
            type: 'post',
            url: url,
            dataType: 'json',
            async: true,
            success: function (rep) {
                //睡眠 一秒
                setTimeout(function () {
                    if (isLoad) {
                        layer.close(index)
                    }
                    switch (rep.code) {
                        case -1:
                            layer.msg(rep.msg, {icon: 5});
                            break
                        case 1:
                            layer.msg(rep.msg, {icon: 2});
                            break
                        default:
                            layer.msg(rep.msg ? rep.msg : '操作成功', {icon: 1})
                    }


                    if (option.callback && $.isFunction(option.callback)) {
                        option.callback(rep.data)
                    }
                }, 1000)
            },
            error: function (response, textStatus, errorThrown) {
                if (isLoad) {
                    layer.close(index)
                }
                var code = response.status
                try {

                    switch (code) {
                        case 500:
                            layer.msg(textStatus, {icon: 5});
                            break
                        case 404:
                            layer.msg('访问地址不存在', {icon: 2});
                            break
                        default:
                            layer.msg(textStatus, {icon: 2})
                    }
                } catch (e) {
                    layer.msg(e, {icon: 5})
                }

            }
        };

        $.extend(opt, option)
        $.ajax(opt)
    }


    /**
     * 睡眠
     * @param numberMillis 单位为毫秒
     */
    function sleep(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
    }


    /**
     * 表单转json数据
     * @param target
     * @returns {{}}
     */
    function serializeJson(target) {

        var $node = jq(target)
        var serializeObj = {}
        var array = $node.serializeArray()
        var str = $node.serialize()
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value)
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value]
                }
            } else {
                serializeObj[this.name] = this.value
            }
        })
        return serializeObj
    }

    //UUID生成
    function uuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [], i;
        radix = radix || chars.length;

        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join('');
    }

    //标签属性快捷写法处理
    function parseQuickAttrValue(value) {
        if (!value || !$.trim(value)) {
            return
        }

        value = value.replace(/\s/g, '')


        if (value.indexOf('function') != -1) {
            layer.msg('暂不支持回调函数写法')
            throw new Error('暂不支持回调函数写法')
        }

        if (value.indexOf('/') != -1) {
            layer.msg('暂不支持回调函数写法')
            throw new Error('暂不支持注释或者正则写法')
        }

        if (value.match(/['"]{1}/)) {
            layer.msg('语法不正确')
            throw new Error('语法不正确')
        }

        if (value.substring(0, 1) != '{' || value.substring(value.length - 1, value.length) != '}') {
            layer.msg('语法不正确')
            throw new Error('语法不正确')
        }


        // 先处理中括号的数据
        var newVal = ''

        var signType = 0
        var word = ''
        var rep = /(^[0-9]*$)|(^true$)|(^false$)/
        for (i in value) {
            var ele = value[i]

            signType = ele == ':' ? 1 : ele == '[' ? 2 : signType
            newVal += ele == '[' ? ':[' : ''

            if (signType == 1 && (ele == '}' || ele == ',')) {
                word = word.replace(':', '')
                newVal += rep.test(word) ? ":" + word : ":'" + word + "'"
                signType = 0
                word = ''
            }

            if (signType == 2 && (ele == ']' || ele == ',')) {
                var newWord = word.indexOf(':[') != -1 ? word.substring(2, word.length) : word.substring(0, 1) == ',' ? word.substring(1) : word

                if (!rep.test(newWord)) {

                    if (ele == ']') {
                        newVal += "'" + newWord + "'"
                    } else {
                        newVal += "'" + newWord + "',"
                    }
                } else {
                    if (ele == ']') {
                        newVal += newWord
                    } else {
                        newVal += newWord + ","
                    }
                }

                if (ele == ']') {
                    signType = 0
                }
                word = ''
            }

            if (signType == 0) {
                newVal += ele
            } else {
                word += ele
            }

        }
        return newVal
    }

    console.info(1253)

    exports('utl',
        {
            jq: jq
            , ajax: ajax
            , sleep: sleep
            , serializeJson: serializeJson
            , uuid: uuid
            , attrParse: parseQuickAttrValue
        }
    )
})
